<?php
function_exists('UnixPath')  || die('OK');

	$ACT = array('list', 'add', 'aok', 'edit', 'eok', 'del', 'form'); //', 'create', 'cok' , bind', 'bok',
	in_array($_GET['act'], $ACT) || $_GET['act'] = 'list';
	//$html['tpl_right_act'] = $_GET['act'];

	$_GET['pid']	= (int) $_GET['pid'];
	$_GET['id']	= (int) $_GET['id'];

	$P = E::$DB->one('_table_list', 'id='.$_GET['pid']);
	$P['id'] || A::msg('错误了!');

	$body['navlist'] = array(
		'list' => '字段列表',
		'add' => '添加字段',
	);

	$body['navslist'] = array(
		array('修改表', '?mod='.$_GET['mod'].'&fun=table&act=edit&id='.$P['id']),
		array('更新表单', '?mod='.$_GET['mod'].'&fun=field&act=form&pid='.$P['id']),
	);

	if( $P['isGroup'] ){
		array_push($body['navslist'],  array('分组管理', '?mod='.$_GET['mod'].'&fun=field_group&act=list&pid='.$P['id']));
		$Groups	= E::$DB->ary('_table_group', 'tid=' . $_GET['pid'] .' ORDER BY iOrder DESC , id ASC' , 'id, name', 'id' );
		$tpl->assign_by_ref('Groups', $Groups);
	}

	$body['_url'] = '&pid='.$P['id'];
	$body['url'] = $html['url'].$body['_url'];
	$body['node_tree'] = '<a href="?mod=_super&fun=table&act=list">数据表列表</a> <small>&#187;</small> '.$P['description'].' <small>&#187;</small>  <a href="'.$body['url'].'&act=list">字段管理</a>'; 
	E::$DB->_tab = '_table_field';

/*************动作************/

if( $_GET['act'] === 'create' ){
	$body['navlist']['create']	= '<b style="color:#f00;">创建字段</b>';

	$L = E::$DB->all('_table_field', 'tid='. $P['id'].' order BY orderId DESC , id ASC  ');

	$Fields	= array();

	$rs	= mysql_query('SHOW FIELDS FROM ' .$P['tableName'],  E::$DB->_handle);

	if( mysql_error() === '' ){
		while( $field  = mysql_fetch_array($rs, 1)){
			$Fields[$field['Field']]	= $field ;
		}
		foreach($L as $k=>&$v){
			if( $Fields[$v['fieldKey']] ){
				unset($L[$k]);
			}
		}
		unset($v);
	}

	$datatypes	= include( B_DIR . '/_res/const/datatypes.php');

	foreach($L as &$v){
		
	}
	unset($v);
	print_r($L);
	$tpl->assign_by_ref('datatypes', $datatypes);
}

if( $_GET['act'] === 'add' ){
	include(B_DIR . '/_res/const/elements.php');
	$body['elements'] = &$elements;

	$body['need_checkbox']	= param_checkbox();
	
	$param_B	= include(B_DIR . '/_res/tree/param_B.php' );
	$body['param_radio']	= param_radio_group($param_B, $L['bindId']);


	$tmp	=  array_flip (E::$DB->ary('_table_field', 'tid='.$P['id'].' AND elementType="xhr" ORDER BY orderId DESC, id ASC','id,DepField', 'id', 'DepField'));

	$body['form_xhr'] = E::$DB->ary('_table_field', 'tid='.$P['id'].' AND  ( elementType="select" OR elementType="xhr")  ORDER BY orderId DESC, id ASC', 'id,fieldName', 'id', 'fieldName');

	foreach($body['form_xhr'] as $k=>&$v){
		if( $tmp[$k] ){
			unset($body['form_xhr'][$k]);
		}
	}
	$L['gid']	= (int) $_GET['gid'];
	unset($tmp);
	
	$body['xhr_need']	= xhr_need( 0 );
}
	
if( $_GET['act'] === 'aok' ){	
	$L = E::$DB->one('_table_field', 'fieldKey="'.$_POST['fieldKey'].'" AND tid='.$P['id']);
	$L['id'] && A::msg('字段值已经在改表存在!', '', 1,1);
	$_POST['tid'] = $P['id'];

	if( is_array($_POST['need']) ) foreach($_POST['need'] as &$_needs){
		if( is_array($_needs) ) foreach($_needs as &$_need){
			$_need	= 1;
		}
	}
	$_POST['need'] = @serialize($_POST['need']);

	E::$DB->insert('_table_field', 'tid,orderId,fieldKey,fieldName,isEdit,isForce,DepField,elementType,regs,alert,note,need,size,bindId,isPower,gid');
	A::msg('添加字段 ' . $_POST['fieldName'] . ' 完成!', $_POST['jurl'], 1, 1 );
}


  
if( $_GET['act'] === 'edit' ){
	$L = E::$DB->one('_table_field', 'id='.$_GET['id']);
	$L['id'] || A::msg('无效的表', $_POST['jurl'], 1, 1 );

	include(B_DIR . '/_res/const/elements.php');
	$body['elements'] = &$elements;
	$L['need'] = unserialize($L['need']);

	$body['need_checkbox']	= param_checkbox($L);
	$param_B	= include(B_DIR . '/_res/tree/param_B.php' );	
	$body['param_radio']	= param_radio_group($param_B, $L['bindId']);

	
	$tmp	=  array_flip (E::$DB->ary('_table_field', 'tid='.$P['id'].' AND elementType="xhr" ORDER BY orderId DESC, id ASC','id,DepField','id','DepField'));
	unset($tmp[$L['DepField']]);
	$body['form_xhr'] = E::$DB->ary('_table_field', 'tid='.$P['id'].' AND  ( elementType="select" OR elementType="xhr")  ORDER BY orderId DESC, id ASC','id,fieldName','id','fieldName');
	foreach($body['form_xhr'] as $k=>&$v){
		if( $tmp[$k] ){
			unset($body['form_xhr'][$k]);
		}
	}
	unset($tmp);
	$body['xhr_need']	= xhr_need( $L['id'] );
	$L['need_json']		= json_encode($L['need']);
}

if( $_GET['act'] === 'eok' ){
	
	$L = E::$DB->one('_table_field', 'fieldKey="' . $_POST['fieldKey'] . '" AND tid=' . $P['id'] . ' AND id<>' . $_GET['id']);
	$L['id'] && A::msg('字段值已经在改表存在!', '', 1, 1);

	$L = E::$DB->one('_table_field', 'id=' . $_GET['id']);
	$L['id'] || A::msg('无效的表', $_POST['jurl'], 1, 1 );

	if( is_array($_POST['need']) ) foreach($_POST['need'] as &$_needs){
		if( is_array($_needs) ) foreach($_needs as &$_need){
			$_need	= 1;
		}
	}
	$_POST['need'] = serialize($_POST['need']);

	E::$DB->update('_table_field', 'orderId,fieldKey,fieldName,isEdit,isForce,DepField,elementType,regs,alert,note, need,size,bindId, isPower , gid ', 'id='.$L['id'].'');
	A::msg('修改字段 '. $_POST['fieldName'] .' 完成!', $_POST['jurl'], 1, 1 );
}


if( $_GET['act'] === 'del' ){
	$L = E::$DB->one('_table_field', 'id='.$_GET['id']);
	$L['id'] || A::msg('无效的节点', $_POST['jurl'], 1, 1 );
	E::$DB->query('DELETE FROM  '.E::$DB->_tab.' where id='.$L['id'].'');
	C::tree('_table_field', $order, $cache_file);
	A::msg('删除字段 ' . $L['fieldName'] . ' 完成!', $_POST['jurl'], 1, 1 );
}


if( $_GET['act'] === 'list' ){
	//$p = E::$DB->page('_table_field', 'tid='.$P['id'] );
	$L = E::$DB->all('_table_field', 'tid='. $P['id'].' order BY  gid ASC, orderId DESC , id ASC  ');
	include(B_DIR . '/_res/const/elements.php');
	$tpl->assign_by_ref('elements', $elements);

	$Fields	= array();


	$rs	= mysql_query('SHOW FIELDS FROM ' .$P['tableName'],  E::$DB->_handle);

	$isNeedCreate	= false;
	if( mysql_error() === '' ){
		while( $field  = mysql_fetch_array($rs, 1)){
			$Fields[$field['Field']]	= $field ;
		}

		foreach($L as &$v){
			if( $Fields[$v['fieldKey']] ){
				$v['_Type']	= $Fields[$v['fieldKey']]['Type'];
			}else{
				$isNeedCreate	= true;
				$v['_Type']	= '<a style="color:#f30;">不存在</a>';
			}
			unset( $Fields[$v['fieldKey']] );
		}
		unset($v);
		$tips	= array();
		foreach($Fields as $key => $v){
			$tips[]	=  '<b>'. $key . '</b>  ' . $v['Type'] . '';
		}
		unset($v);
		$tpl->assign('tips', '数据表 <b>'.$P['tableName'].'</b> 的其他字段<br/>　　　' . join('<br/>　　　', $tips));


	}else{
		foreach($L as &$v){
			$v['_Type']	= '<a style="color:#f30;">不存在</a>';
		}
		unset($v);
		
		$isNeedCreate	= true;
		$tpl->assign('tips', '数据表 <b>'.$P['tableName'].'</b> 不存在!');
	}

	if( $isNeedCreate ){
		// $body['navlist']['create']	= '<b>创建字段</b>';
	}
}


if( $_GET['act'] === 'form' ){
	$body['navslist'][1]['col']	= '#f00';
	form_cache($P['id']);
}

function param_radio_group($a, $key=''){
	if(is_array($a)){
		foreach($a as $k=>$v){
			if( !$v['isParent'] ){
				continue; 
			}
			$dep = $v['deep'] ;
			$isc = ( $v['id'] == $key ) ?' checked="true"' :'';
			$s .= '<label for="mod_'.$k.'"><input type="radio" name="bindId" value="'.$k.'" id="mod_'.$k.'" '.$isc.'/>'.$v['paramName'].'</label>';
			if(is_array($v['child'])){
				$s .= $tab.'<div id="mod_'.$k.'_" class="checkboxdep'.$dep.'">'.param_radio_group($v['child'], $key).'</div>';
			}
		}
	}
	return $s;
}

function param_checkbox( $L = array() ){
	global $P;
	// $xL = E::$DB->ary('_table_field', 'tid='.$P['id'].' AND bindId!=0 AND elementType!="password" AND elementType!="text"  ORDER BY orderId DESC, id ASC');
	$L_id	= (int) $L['id'];
	$xL = E::$DB->ary('_table_field', 'tid=' . $P['id'] . ' AND bindId!=0  AND (elementType="select" OR elementType="radio" OR elementType="checkbox") AND id!=' . $L_id . '  ORDER BY orderId DESC, id ASC');
	$a = array(); 
	$s = '';
	foreach($xL as $k=>$v){
		$s .= '<div class=""><a>字段: '.$v['fieldName'].' =&gt; '.$v['fieldKey'].'</a><div class="checkboxdep1">';
		$l = E::$DB->all('_super_param', 'pid='.$v['bindId'].' ORDER BY orderId DESC, id ASC');
		$id = $v[id];
		foreach($l as $_k=>$_v){
			$_id	= $_v['paramValue']!='' ? $_v['paramValue'] : $_v['id'];
			//$val	= $_v['paramValue'] ? $_v['paramValue'] : $_id;
			$s .= '<label><input type="checkbox" name="need['.$id.']['.$_id.']" value="1" /> '.$_v['paramName'].'</label>';
		}
		$s .= '</div></div>';
	}
	E::$DB->_tab = '_table_field';	
	return $s;
}

function xhr_need( $self_id ){
	$self_id	= (int) $self_id ;
	$bind_id	= (int) $bind_id ;
	global $P;
	$parents	= E::$DB->ary('_table_field', 'tid=' . $P['id'] . ' AND  (elementType="select" OR elementType="xhr")  ORDER BY orderId DESC, id ASC','id,fieldName,bindId','id');
	$xhr = E::$DB->ary('_table_field', 'tid=' . $P['id'] . ' AND  elementType="xhr" AND id!='. $self_id . ' AND DepField!='. $self_id . '  ORDER BY orderId DESC, id ASC','id,fieldName,fieldKey,DepField','DepField');

	$List	= array();
	$List2	= array();
	foreach($xhr as $fid => $_xhr){
		$param_id	= $parents[$_xhr['DepField']]['bindId'];
		if( !$param_id ){
			continue;
		}
		$List[$param_id]	= E::$DB->ary('_super_param', 'pid='. $param_id .' ORDER BY orderId DESC, id ASC', 'id,paramName', 'id', 'paramName');

		foreach($List[$param_id] as $param_id2 => $_val){
			$List2[$param_id][$param_id2]	= E::$DB->ary('_super_param', 'pid='. $param_id2 .' ORDER BY orderId DESC, id ASC', 'id,paramName,paramValue', 'id');
		}

	}
	if( empty($List) ){
		return "";
	}

	$bindId_key	= E::$DB->ary('_table_field', 'tid='.$P['id'].' AND  (elementType="select" OR elementType="xhr")  ORDER BY orderId DESC, id ASC','id,fieldName,bindId','bindId');

	$shtml	= "";
	foreach( $List as $pId => $pVals){
		$p_fid		= $bindId_key[$pId]['id'];
		$fid		= $xhr[$p_fid]['id'];
		$fname		= $xhr[$p_fid]['fieldName'];
		$fkey		= $xhr[$p_fid]['fieldKey'];
		$shtml	.= "<div> 字段:" . $fname . ' => ' . $fkey . "<div class='checkboxdep1'>";
		foreach($pVals as $pId2=>$pVal2){
			$shtml	.= "<div class='checkboxdep2'>$pVal2<div class='checkboxdep3'>";
			foreach($List2[$pId][$pId2] as $id=>$Val){
				$id		= $Val['paramValue']!='' ? $Val['paramValue'] : $id ;
				$HtmlId	= "xhrNeed_" .$fid . "_" . $pId2 . "_" . $id;
				$shtml	.= '<label for="'.$HtmlId.'"><input id="'.$HtmlId.'" name="need['. $fid . ']['. $id .']" type="checkbox" value="1" />' . $Val['paramName'] . '</label>';
			}
			$shtml	.= "</div></div>";
		}
		$shtml	.= "</div></div>";
	}
	
	return $shtml;
}

function form_cache($id){
	$id	= (int) $id;
	$T	= E::$DB->one('_table_list', 'id=' . $id );
	if( empty($T) ){
		die('Error On ' . __FILE__ . ' ' . __LINE__ );
	}
	if( $T['isForm83'] ){
		new Form83($id);
	}else{
		new xform($id);
	}
}

if($_GET['all']) {
	C::table();
}